package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {

    @Override
    public ResponseResult login(AdUserDto dto) {


        //参数校验
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请输入用户名或密码");
        }
        //根据用户名查询数据库获取用户数据
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser user = getOne(queryWrapper);
        //判断用户是否存在
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //存在则校验密码
        String password = dto.getPassword();
        String userSalt = user.getSalt();
        password = DigestUtils.md5DigestAsHex((password + userSalt).getBytes());
        if (!password.equals(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //通过则返回前端数据 及token信息
        Map<String,Object> map = new HashMap<>();
        user.setPassword("");
        user.setSalt("");
        map.put("user",user);
        String token = AppJwtUtil.getToken(user.getId().longValue());
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
